<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\model;

use buwang\base\BaseModel;
use buwang\traits\JwtTrait;
use think\facade\Db;

/**管理员角色中间表
 * Class AuthNode
 * @package app\manage\model
 */
class AuthGroupAccess extends BaseModel
{
    protected $pk = 'id';
    // 表名
    protected $name = 'auth_group_access';
    protected $updateTime = '';

    protected $deleteTime = '';


    //得到列表
    public static function getlist($is_array = false)
    {
        //$list  =  Db::name('auth_group_access')->select();
        // var_dump($list);die;
        //得到所有登录用户
        $groups = Admin::valiWhere()->select()->toArray();
        //返回数据
        $res = array();
        foreach ($groups as $group) {
            $data = $group;
            $data['rules'] = null;
            $data['auth_group_access'] = null;
            if ($is_array) $data['rules'] = [];
            if ($is_array) $data['auth_group_access'] = [];
            //查询所有角色，以逗号拼接
            $rules = self::valiWhere()->where('uid', $group['id'])->where('scopes', 'admin')->column('group_id');
            $names = self::valiWhere()->where('uid', $group['id'])->where('scopes', 'admin')->column('name');
            if ($rules) {
                $data['rules'] = implode(",", $rules);
                if ($is_array) $data['rules'] = $rules;
            }
            if ($names) {
                $data['auth_group_access'] = implode(",", $names);
                if ($is_array) $data['auth_group_access'] = $names;
            }
            $res[] = $data;
        }
        return $res;
    }


    //得到所有租户列表
    public static function getMemberlist($member_id, $is_array = false)
    {
        //$list  =  Db::name('auth_group_access')->select();
        // var_dump($list);die;
        //得到当前租户和其子租户
        $groups = Member::where(function ($query) use ($member_id) {
            $query->where('id', $member_id)->whereOr('parent_id', $member_id);
        })->select()->toArray();

        // $groups  =   Admin::valiWhere()->select()->toArray();
        //返回数据
        $res = array();
        foreach ($groups as $group) {
            $data = $group;
            $data['rules'] = null;
            $data['auth_group_access'] = null;
            if ($is_array) $data['rules'] = [];
            if ($is_array) $data['auth_group_access'] = [];
            //查询所有角色，以逗号拼接
            $rules = self::valiWhere()->where('uid', $group['id'])->where('scopes', 'member')->column('group_id');
            $names = self::valiWhere()->where('uid', $group['id'])->where('scopes', 'member')->column('name');
            if ($rules) {
                $data['rules'] = implode(",", $rules);
                if ($is_array) $data['rules'] = $rules;
            }
            if ($names) {
                $data['auth_group_access'] = implode(",", $names);
                if ($is_array) $data['auth_group_access'] = $names;
            }
            $res[] = $data;
        }
        return $res;
    }


    //得到管理员一条数据
    public static function getFind($id)
    {
        //得到所有角色
        $group = Admin::valiWhere()->find($id);
        //返回数据
        $res = array();
        if ($group) {
            $res = $group->toArray();
            $res['rules'] = null;
            //查询所有角色，以逗号拼接
            $rules = self::valiWhere()->where('uid', $group['id'])->where('scopes', 'admin')->column('group_id');
            if ($rules) {
                $res['rules'] = implode(",", $rules);

            }

        }
        return $res;
    }

    //得到租户一条数据
    public static function getMemberFind($id)
    {
        //得到所有角色
        $group = Member::valiWhere()->find($id);
        //返回数据
        $res = array();
        if ($group) {
            $res = $group->toArray();
            $res['rules'] = null;
            //查询所有角色，以逗号拼接
            $rules = self::valiWhere()->where('uid', $group['id'])->where('scopes', 'member')->column('group_id');
            if ($rules) {
                $res['rules'] = implode(",", $rules);

            }

        }
        return $res;
    }


    /*
* 设置查询初始化条件
* @param string $alias 表别名
* @param object $model 模型实例化对象
* @return object
* */
    public static function valiWhere($alias = '', $model = null)
    {
        $model = is_null($model) ? new self() : $model;
        if ($alias) {
            $model = $model->alias($alias);
            $alias .= '.';
        }
        // return  $model->where("{$alias}delete_time", 0);
        return $model;
    }


    /**更新权限
     * @param $id
     * @param $rules
     */
    public static function updateRule($id, $rules, $scopes = 'admin', $trans = false)
    {
        // var_dump($id);die;//常用函数
        if ($trans) {
            self::startTrans();
        }
        $res = $res1 = $res2 = true;
        try {
            //删除之前的权限
            $res1 = self::destroy(function ($query) use ($id, $scopes) {
                $query->where('uid', '=', $id)->where('scopes', '=', $scopes);
            });
            $all = array();
            //var_dump($res1);die;//常用函数
            $rules = array_unique($rules);
            //添加新的权限节点
            foreach ($rules as $rule) {
                //得到角色信息
                $node = AuthGroup::find($rule);
                if (!$node) return self::setError('角色不存在');
                $data = [
                    'uid' => $id,
                    'group_id' => $rule,
                    'scopes' => $scopes,
                    'name' => $node['name'],
                ];
                $all[] = $data;
            }
            if ($rules) {
                $self = new self;
                $res2 = $self->saveAll($all);
            }


            $res = $res && $res1 && $res2 && true;
            if ($trans) {
                self::checkTrans($res);
            }
            if (!$res1) return self::setError('删除角色失败');
            if (!$res2) return self::setError('插入角色失败');
        } catch (\Exception $e) {
            if ($trans) {
                self::rollback();
            }
            return self::setError($e->getMessage());
        }
        if (!$res) return self::setError('更新角色失败');

        return $res;

    }

    /**租户注册初始化角色权限组
     * @param $memberId
     * @param bool $trans
     * @return bool
     */
    public static function memberInitRule($id, $trans = false)
    {

        //租户初始化权限组id
        $rules = config('auth.base_role_ids', []);
        if (!$rules) return self::setError('没有配置租户初始化角色');
        //角色是否存在
        $role_ids = AuthGroup::where('id', 'in', $rules)->column('id');
        if (count($role_ids) != count($rules)) return self::setError('租户初始化角色中存在无效角色组');
        if ($trans) {
            self::startTrans();
        }
        $res = $res1 = $res2 = true;
        try {

            //删除之前的权限
            $res1 = self::destroy(function ($query) use ($id) {
                $query->where('uid', '=', $id)->where('scopes', '=', 'member');
            });
            $all = array();
            //var_dump($res1);die;//常用函数
            $rules = array_unique($rules);//去重
            //添加新的权限节点
            foreach ($rules as $rule) {
                //得到角色信息
                $node = AuthGroup::find($rule);
                if (!$node) return self::setError('角色不存在');
                $data = [
                    'uid' => $id,
                    'group_id' => $rule,
                    'scopes' => 'member',
                    'name' => $node['name'],
                ];
                $all[] = $data;
            }
            if ($rules) {
                $self = new self;
                $res2 = $self->saveAll($all);
            }


            $res = $res && $res1 && $res2 && true;

            if ($trans) {
                self::checkTrans($res);
            }
        } catch (\Exception $e) {
            if ($trans) {
                self::rollback();
            }
            if (!$res1) return self::setError('删除角色失败');
            if (!$res2) return self::setError('插入角色失败');
        }
        if (!$res) return self::setError('未知错误');

        return $res;


    }


}
